package de.windeln.marketing.validation;

import javax.annotation.Resource;

import org.joda.time.DateTime;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import de.windeln.marketing.campaign.costinterval.model.CostintervalClientObject;
import de.windeln.marketing.campaign.costinterval.services.interfaces.CostIntervalService;

@Component
public class CostIntervalInBetweenCampaignInterval implements Validator {

	@Resource(name = "costIntervalService")
	private CostIntervalService costIntervalService;

	@Override
	public boolean supports(Class<?> clazz) {
		return clazz == CostintervalClientObject.class;
	}

	@Override
	public void validate(Object target, Errors errors) {
		CostintervalClientObject cico = (CostintervalClientObject) target;
		DateTime campaignStart = new DateTime(costIntervalService.findCampaignStartByCampaignId(cico.getCampaignId()));
		DateTime campaignEnd = new DateTime(costIntervalService.findCampaignEndByCampaignId(cico.getCampaignId()));
		if (campaignStart != null) {
			if (!new DateTime(cico.getCostStart()).isAfter(campaignStart)) {
				errors.rejectValue("costStart", "Costinterval in between Campaigninterval",
						"Costinterval must be in between Campaigninterval, Costinterval Start Date is not allowed to be before Campaigninterval Start Date!");
			}
		}
		if (campaignEnd != null) {
			if (!new DateTime(cico.getCostEnd()).isBefore(campaignEnd)) {
				errors.rejectValue("costEnd", "Costinterval in between Campaigninterval",
						"Costinterval must be in between Campaigninterval, Costinterval End Date is not allowed to be after Campaigninterval End Date!");
			}
		}
	}

}
